package com.coursehub.course.service.impl;

import com.coursehub.course.entity.Chapter;
import com.coursehub.course.repository.ChapterRepository;
import com.coursehub.course.service.ChapterService;
import com.coursehub.course.service.CourseService;
import com.coursehub.shared.exception.ResourceNotFoundException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.coursehub.shared.client.ServiceClient;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 章节服务实现类
 */
@Service
@RequiredArgsConstructor
@Transactional
public class ChapterServiceImpl implements ChapterService {
    
    private static final Logger log = LoggerFactory.getLogger(ChapterServiceImpl.class);
    
    private final ChapterRepository chapterRepository;
    private final CourseService courseService;
    private final ServiceClient serviceClient;
    
    @Value("${coursehub.services.urls.learning-progress:http://localhost:8085}")
    private String learningProgressServiceUrl;
    
    @Override
    public Chapter createChapter(Chapter chapter) {
        log.info("创建章节: {}", chapter.getChapterName());
        
        // 验证课程是否存在
        if (!courseService.existsByCourseId(chapter.getCourse().getCourseId())) {
            throw new ResourceNotFoundException("Course", chapter.getCourse().getCourseId());
        }
        
        // 检查同一课程下是否已存在相同名称的章节
        if (chapterRepository.existsByCourse_CourseIdAndChapterName(
                chapter.getCourse().getCourseId(), chapter.getChapterName())) {
            throw new IllegalArgumentException("该课程下已存在相同名称的章节");
        }
        
        return chapterRepository.save(chapter);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<Chapter> getChapterById(String chapterId) {
        log.info("根据ID获取章节: {}", chapterId);
        return chapterRepository.findById(chapterId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Chapter> getAllChapters() {
        log.info("获取所有章节");
        return chapterRepository.findAll();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Chapter> getChaptersByCourseId(String courseId) {
        log.info("根据课程ID获取章节列表: {}", courseId);
        
        // 验证课程是否存在
        if (!courseService.existsByCourseId(courseId)) {
            throw new ResourceNotFoundException("Course", courseId);
        }
        
        return chapterRepository.findByCourse_CourseId(courseId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<String> getChapterIdsByCourseId(String courseId) {
        log.info("根据课程ID获取章节ID列表: {}", courseId);
        
        // 验证课程是否存在
        if (!courseService.existsByCourseId(courseId)) {
            throw new ResourceNotFoundException("Course", courseId);
        }
        
        return chapterRepository.findChapterIdsByCourseId(courseId);
    }
    
    @Override
    public Chapter updateChapter(String chapterId, Chapter chapter) {
        log.info("更新章节: {}", chapterId);
        
        Chapter existingChapter = chapterRepository.findById(chapterId)
                .orElseThrow(() -> new ResourceNotFoundException("Chapter", chapterId));
        
        // 更新章节信息
        existingChapter.setChapterName(chapter.getChapterName());
        
        return chapterRepository.save(existingChapter);
    }
    
    @Override
    public void deleteChapter(String chapterId) {
        log.info("删除章节: {}", chapterId);
        
        if (!chapterRepository.existsById(chapterId)) {
            throw new ResourceNotFoundException("Chapter", chapterId);
        }
        
        chapterRepository.deleteById(chapterId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Chapter> searchChaptersByName(String chapterName) {
        log.info("根据章节名称搜索章节: {}", chapterName);
        return chapterRepository.findByChapterNameContainingIgnoreCase(chapterName);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean existsByChapterId(String chapterId) {
        return chapterRepository.existsByChapterId(chapterId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean validateChapterBelongsToCourse(String chapterId, String courseId) {
        log.info("验证章节是否属于指定课程: chapterId={}, courseId={}", chapterId, courseId);
        
        Optional<Chapter> chapter = chapterRepository.findById(chapterId);
        return chapter.isPresent() && chapter.get().getCourse().getCourseId().equals(courseId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Chapter> getLearnedChaptersByStudent(String userId, String courseId) {
        log.info("获取学生已学习章节: userId={}, courseId={}", userId, courseId);
        
        try {
            // 调用学习进度服务获取已完成的章节ID列表
            String endpoint = "/api/progress/chapter/user/" + userId + "/course/" + courseId + "/completed";
            List response = serviceClient.get("learning-progress", endpoint, List.class);
            
            if (response != null) {
                List<String> completedChapterIds = (List<String>) response;
                // 根据章节ID列表获取章节详情
                return chapterRepository.findAllById(completedChapterIds);
            }
        } catch (Exception e) {
            log.warn("调用学习进度服务失败，返回空列表: {}", e.getMessage());
        }
        
        return List.of();
    }
    
    @Override
    public void markChapterAsFinished(String userId, String chapterId) {
        log.info("标记章节完成: userId={}, chapterId={}", userId, chapterId);
        
        // 验证章节是否存在
        if (!existsByChapterId(chapterId)) {
            throw new ResourceNotFoundException("Chapter", chapterId);
        }
        
        try {
            // 调用学习进度服务标记章节完成
            String endpoint = "/api/progress/chapter/user/" + userId + "/chapter/" + chapterId + "/complete";
            serviceClient.post("learning-progress", endpoint, null, Void.class);
            log.info("章节标记完成成功: userId={}, chapterId={}", userId, chapterId);
        } catch (Exception e) {
            log.error("调用学习进度服务失败: {}", e.getMessage());
            throw new RuntimeException("标记章节完成失败: " + e.getMessage());
        }
    }
}